package com.rc.saas.mini.charge;

import com.github.dozermapper.core.Mapper;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.constant.PlatformConstant;
import com.rc.saas.mini.hlhtcec2.service.HlhtChargeService;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecPile;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.elec.ElecStationOut;
import com.rc.saas.mini.model.hlht.HlhtOperator;
import com.rc.saas.mini.model.hlht.HlhtTenantOpen;
import com.rc.saas.mini.model.hlht.HlhtTenantOpenStation;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderComment;
import com.rc.saas.mini.service.elec.ElecGunService;
import com.rc.saas.mini.service.elec.ElecPileService;
import com.rc.saas.mini.service.elec.ElecStationOutService;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.hlht.HlhtOperatorService;
import com.rc.saas.mini.service.hlht.HlhtTenantOpenService;
import com.rc.saas.mini.service.hlht.HlhtTenantOpenStationService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.tenant.TenantSettingService;
import com.rc.saas.mini.vo.charge.CommandStartReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import com.rc.saas.mini.vo.hlhtcec2.*;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author wangzhengwei
 * @create 2021/12/21
 * 充电服务
 */
@Component
public class ChargeServiceRouter {
    private static Logger logger = LogManager.getLogger(ChargeServiceRouter.class);

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private TenantSettingService tenantSettingService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private HlhtChargeService hlhtChargeService;

    @Autowired
    private ElecStationOutService elecStationOutService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    @Autowired
    private HlhtTenantOpenStationService hlhtTenantOpenStationService;

    @Autowired
    private HlhtOperatorService hlhtOperatorService;

    /**
     * 根据枪号或二维码获取详情
     *
     * @return
     */
    public TResponse query_gun_detail(MemberInfo memberInfo, String hlhtTenantCode, String hlhtOperatorId, String gunNo, String qrCode) {
        String tenantCode = memberInfo.getTenantCode();

        //运营商自己的桩
        ElecStation elecStation = null;
        ElecGun elecGun = null;
        if (StringUtils.isBlank(hlhtOperatorId)) {
            //枪信息
            elecGun = elecGunService.selectByGunNo(gunNo);

            if (elecGun == null) {
                return TResponse.FAIL("充电枪不存在");
            }
            if (elecGun.getHlhtOperatorId() != null) {
                hlhtOperatorId = elecGun.getHlhtOperatorId();
            }


            ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
            //枪状态

            //离线
            if (0 == pile.getStatus()) {
                return TResponse.FAIL("输入的充电枪离线");
            }

            if (!"1".equals(elecGun.getOperateStatus())) {
                return TResponse.FAIL("输入的充电枪未上线");
            }

            elecStation = elecStationService.selectByPrimaryKey(elecGun.getElecStationId());
            if (elecStation == null) {
                return TResponse.FAIL("桩群不存在");
            }
            if (!"1".equals(elecGun.getOperateStatus())) {
                return TResponse.FAIL("输入的充电枪离线");
            }

            if (!elecStation.getTenantCode().equals(tenantCode)) {
                //其它SAAS运营商桩
                hlhtTenantCode = elecStation.getTenantCode();
            }

        }

        if (StringUtils.isBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {//运营商自己的桩
            return chargeService.query_gun_detail(memberInfo, elecStation, elecGun, hlhtTenantCode, hlhtOperatorId, gunNo, qrCode);
        }
        return null;
        //else if (StringUtils.isNotBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {
        //    //其它SAAS运营商桩 {
        //    //内部互联站点开放
        //    HlhtTenantOpen hlhtTenantOpen = hlhtTenantOpenService.selectHlhtTenantOpenBySaas(memberInfo.getTenantCode(), elecStation.getTenantCode(), "0");
        //    if (hlhtTenantOpen == null) {
        //        return TResponse.FAIL("未开放互联关系");
        //    }
        //    HlhtTenantOpenStation hlhtTenantOpenStation = hlhtTenantOpenStationService.selectByhlhtTenantOpenStationBySaas(memberInfo.getTenantCode(), elecStation.getTenantCode(),
        //            elecStation.getElecStationId(), "0");
        //    if (hlhtTenantOpenStation == null) {
        //        return TResponse.FAIL("未开放该互联站点");
        //    }
        //    return chargeService.query_gun_detail(memberInfo, elecStation, elecGun, hlhtTenantCode, hlhtOperatorId, gunNo, qrCode);
        //}
        //else {
        //    //第三方运营商
        //    HlhtOperator hlhtOperator = hlhtOperatorService.selectByPrimaryKey(hlhtOperatorId);
        //    if (hlhtOperator == null) {
        //        return TResponse.FAIL(tenantCode + ":找不到运营商信息");
        //    }
        //
        //    //枪信息
        //    elecGun = elecGunService.selectByGunNo(gunNo);
        //    if (elecGun == null) {
        //        return TResponse.FAIL("充电枪不存在");
        //    }
        //    ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        //    //枪状态
        //    //离线
        //    if (0 == pile.getStatus()) {
        //        return TResponse.FAIL("桩群离线");
        //    }
        //    if (!"1".equals(elecGun.getOperateStatus())) {
        //        return TResponse.FAIL("输入的充电枪未上线");
        //    }
        //
        //
        //    elecStation = elecStationService.selectByPrimaryKey(elecGun.getElecStationId());
        //    if (elecStation == null) {
        //        return TResponse.FAIL("桩群不存在");
        //    }
        //    if (!"1".equals(elecGun.getOperateStatus())) {
        //        return TResponse.FAIL("桩群离线");
        //    }
        //    return chargeService.query_gun_detail(memberInfo, elecStation, elecGun, hlhtTenantCode, hlhtOperatorId, gunNo, qrCode);
        //}
    }


    /**
     * 充电前用户余额检查
     */
    public TResponse checkStartMemberAccount(MemberInfo memberInfo, MemberAccount memberAccount,
                                             String hlhtTenantCode, String hlhtOperatorId, String accountType) {
        return chargeService.checkStartMemberAccount(memberInfo, memberAccount, hlhtTenantCode, hlhtOperatorId, accountType);
    }

    /**
     * 请求启动充电
     */
    public TResponse assembleStartChargeResult(CommandStartReq commandStartReq, MemberInfo memberInfo, String hlhtTenantCode, String hlhtOperatorId,
                                               ElecStation elecStation, ElecGun elecGun, Integer limitSoc, String accountType, String ticketUsingType, String carNum) {
        String tenantCode = commandStartReq.getTenantCode();

        logger.info(tenantCode + "-" + commandStartReq.getHlhtTenantCode() + "/" + commandStartReq.getHlhtOperatorId() + ":启动充电,memberId:{},gunNo:{},accountType:{}",
                commandStartReq.getMemberId(), commandStartReq.getGunNo(), commandStartReq.getAccountType());


        //运营商自己+SAAS互联运营商的桩,第三方无效
        if (org.apache.commons.lang.StringUtils.isBlank(hlhtOperatorId)) {
            if (elecGun.getStatus() == 0) {
                return TResponse.FAIL("当前充电枪未插枪");
            }
            if (elecGun.getStatus() == 1) {
                return TResponse.FAIL("当前充电枪使用中");
            }

            //是否优先使用桩群的SOC,如果不设置优先,将以会员的设置为准,0否,1是 默认0
            //if (elecStation.getLimitSocFirst().equals("1") && elecStation.getLimitSoc() != null && elecStation.getLimitSoc() > 0) {
            //    Integer charge_default_limit_soc=elecStation.getLimitSoc();
            //    limitSoc = charge_default_limit_soc;
            //}else {
            //保存SOC限高
            if (limitSoc == null) {
                Integer charge_default_limit_soc = tenantSettingService.query_charge_max_soc(memberInfo.getTenantCode());

                limitSoc = charge_default_limit_soc;
            } else {
                if (limitSoc > PlatformConstant.MAX_SOC || limitSoc <= PlatformConstant.MIN_SOC) {
                    limitSoc = PlatformConstant.DEFAULT_SOC;
                }
            }
            //}

            MemberInfo updateMemberInfo = new MemberInfo();
            updateMemberInfo.setMemberId(memberInfo.getMemberId());
            updateMemberInfo.setLimitSoc(limitSoc);
            memberInfoService.updateByPrimaryKeySelective(updateMemberInfo);
        }

        //各种类型的充电方式
        //if (org.apache.commons.lang.StringUtils.isBlank(hlhtTenantCode) && org.apache.commons.lang.StringUtils.isBlank(hlhtOperatorId)) {//运营商自己的桩
        logger.info(tenantCode + "-" + hlhtTenantCode + ":SAAS启动充电,memberId:{},gunNo:{},accountType:{}",
                memberInfo.getMemberId(), elecGun.getGunNo(), accountType);
        //下达指令
        StartChargeResult result = chargeService.assembleStartChargeResult(commandStartReq);

        WxStartChargeResult appStartChargeResult = dozerMapper.map(result, WxStartChargeResult.class);
        appStartChargeResult.setFailMsg(appStartChargeResult.getFailReason());
        return TResponse.SUCCESS_DATA(appStartChargeResult);
        //}
        //return TResponse.FAIL();

        //else if (org.apache.commons.lang.StringUtils.isNotBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {//其它SAAS运营商桩
        //    logger.info(tenantCode + "-" + hlhtTenantCode + ":其它SAAS运营商桩,memberId:{},gunNo:{},accountType:{}",
        //            memberInfo.getMemberId(), elecGun.getGunNo(), accountType);
        //
        //    //下达指令
        //    StartChargeResult result = chargeService.assembleStartChargeResult(commandStartReq);
        //
        //    WxStartChargeResult appStartChargeResult = dozerMapper.map(result, WxStartChargeResult.class);
        //    appStartChargeResult.setFailMsg(appStartChargeResult.getFailReason());
        //    return TResponse.SUCCESS_DATA(appStartChargeResult);
        //} else {//第三方运营商
        //    logger.info(tenantCode + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":HLHT启动充电,memberId:{},gunNo:{},accountType:{},{}",
        //            memberInfo.getMemberId(), elecGun.getGunNo(), accountType, carNum);
        //
        //    return hlhtChargeService.assembleStartChargeResult(commandStartReq, memberInfo,
        //            hlhtOperatorId, elecStation, elecGun, limitSoc, accountType, ticketUsingType, carNum);
        //}
    }

    /**
     * 查询充电状态，充电过程中调用
     */
    public TResponse assembleEquipChargeStatusResult(CommandStartReq commandStartReq, MemberInfo memberInfo, OrderComment orderComment,
                                                     String hlhtTenantCode, String hlhtOperatorId) {

        WxEquipChargeStatusResult result = null;
        //各种类型的充电
        if (StringUtils.isBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {//运营商自己的桩
            logger.info(orderComment.getTenantCode() + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":SAAS查询充电状态,MemberId:{},outOrder:{},orderNum:{}",
                    memberInfo.getMemberId(), orderComment.getOutOrderNum(), orderComment.getOrderNum());

            result = chargeService.assembleEquipChargeStatusResult(commandStartReq);
            convertResultToChange(result, orderComment, memberInfo);
        } else if (StringUtils.isNotBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {
            logger.info(orderComment.getTenantCode() + "-" + hlhtTenantCode + ":SAAS HLHT查询充电状态,MemberId:{},outOrder:{},orderNum:{}",
                    memberInfo.getMemberId(), orderComment.getOutOrderNum(), orderComment.getOrderNum());
            result = chargeService.assembleEquipChargeStatusResult(commandStartReq);
            convertResultToChange(result, orderComment, memberInfo);
        } else {
            logger.info(commandStartReq.getTenantCode() + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":HLHT查询充电状态,MemberId:{},outOrderNum:{},orderNum:{}",
                    memberInfo.getMemberId(), orderComment.getOutOrderNum(), orderComment.getOrderNum());
            TResponse response = hlhtChargeService.assembleEquipChargeStatusResult(commandStartReq);
            result = (WxEquipChargeStatusResult) response.getData();
        }
        if (result != null) {
            ElecStation elecStation = elecStationService.selectByPrimaryKey(orderComment.getElecStationId());
            ElecGun elecGun = elecGunService.selectByPrimaryKey(orderComment.getElecGunId());
            result.setStationName(elecStation.getStationName());
            result.setGunNo(elecGun.getGunNo());
            result.setGunNum(elecGun.getGunNum());
        }
        return TResponse.SUCCESS_DATA(result);
    }

    /**
     * 请求停止充电,如果成功StartChargeSeqStat需回复3（停止中）
     */
    public TResponse assembleStopChargeResult(CommandStopReq commandStopReq, MemberInfo memberInfo, OrderComment orderComment,
                                              ElecGun elecGun, String hlhtTenantCode, String hlhtOperatorId) {

        if (StringUtils.isBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {//运营商自己的桩
            //如果发送停止命令时，枪的状态不是充电中，并且订单生成时间大于100秒（防止枪状态与平台不同步）。那么直接后台结算订单。
            if (!"1".equals(elecGun.getStatus()) && (System.currentTimeMillis() - orderComment.getStartTime().getTime()) / 1000 > 100) {
                logger.warn(commandStopReq.getTenantCode() + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":发送停止命令时，枪已停止订单自动结算，outOrderNum:{},orderNum:{}",
                        orderComment.getOutOrderNum(), orderComment.getOrderNum());
            }

            logger.info(commandStopReq.getTenantCode() + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":结束充电,gunNo:{},outOrderNum:{},orderNum:{}",
                    elecGun.getGunNo(), orderComment.getOutOrderNum(), orderComment.getOrderNum());

            StopChargeResult result = chargeService.assembleStopChargeResult(commandStopReq);
            WxStopChargeResult wxStopChargeResult = dozerMapper.map(result, WxStopChargeResult.class);
            wxStopChargeResult.setFailMsg(wxStopChargeResult.getFailReason());
            return TResponse.SUCCESS_DATA(wxStopChargeResult);
        } else if (StringUtils.isNotBlank(hlhtTenantCode) && StringUtils.isBlank(hlhtOperatorId)) {
            //如果发送停止命令时，枪的状态不是充电中，并且订单生成时间大于100秒（防止枪状态与平台不同步）。那么直接后台结算订单。
            if (!elecGun.getStatus().equals("1") && ((System.currentTimeMillis() - orderComment.getStartTime().getTime()) / 1000 > 100)) {
                logger.warn(commandStopReq.getTenantCode() + "-" + hlhtTenantCode + ":发送停止命令时，枪已停止订单自动结算，outOrderNum:{},orderNum:{}",
                        orderComment.getOutOrderNum(), orderComment.getOrderNum());
            }

            logger.info(commandStopReq.getTenantCode() + "-" + hlhtTenantCode + ":结束充电,gunNo:{},outOrderNum:{},orderNum:{}",
                    elecGun.getGunNo(), orderComment.getOutOrderNum(), orderComment.getOrderNum());

            StopChargeResult result = chargeService.assembleStopChargeResult(commandStopReq);
            WxStopChargeResult appStopChargeResult = dozerMapper.map(result, WxStopChargeResult.class);
            appStopChargeResult.setFailMsg(appStopChargeResult.getFailReason());

            return TResponse.SUCCESS_DATA(appStopChargeResult);
        } else {//第三方运营商
            logger.info(commandStopReq.getTenantCode() + "-" + hlhtTenantCode + "/" + hlhtOperatorId + ":HLHT结束充电,gunNo:{},outOrderNum:{},orderNum:{}",
                    elecGun.getGunNo(), orderComment.getOutOrderNum(), orderComment.getOrderNum());

            return hlhtChargeService.assembleStopChargeResult(commandStopReq);
        }
    }

    /**
     * 转换对象
     */
    public WxEquipChargeStatusResult convertResultToChange(WxEquipChargeStatusResult result, OrderComment orderComment, MemberInfo member) {
        result.setMemberId(orderComment.getMemberId());
        if (result.getVoltageA() == null) {
            result.setVoltageA(BigDecimal.ZERO);
        }
        if (result.getCurrentA() == null) {
            result.setCurrentA(BigDecimal.ZERO);
        }
        //是否需要车牌 （0否 1是)
        ElecStationOut elecStationOut = elecStationOutService.selectByStationId(orderComment.getElecStationId(), member.getTenantCode());
        if (elecStationOut != null) {
            result.setNeedCarNum("0".equals(elecStationOut.getIsNeedNumber()) ? "1" : "0");
        } else {
            result.setNeedCarNum("1");
        }

        result.setSurplusTime(chargeService.getRemainChargingTime(orderComment.getOrderNum()));
        result.setTemperatureHigh(chargeService.getTemperatureHigh(orderComment.getOrderNum()));
        result.setPower(String.valueOf(result.getVoltageA().multiply(result.getCurrentA()).setScale(2, BigDecimal.ROUND_HALF_UP)));
        logger.info("功率:{}", result.getPower());
        result.setMobile(member.getMobile());
        return result;
    }

}

